#include <iostream>
#include <cstdio>
#include <cassert>
#include <fstream>
#include <sys/wait.h>
#include "../utils/message.h"
#include "syncmessage.h"

using namespace std;

key_t gMessageKey;
int gMessageType;
ofstream gLogFile;

string gLocalPath, gRemotePath;

string getCurrentDate() {
	char date[50];
	time_t rawtime;
	time(&rawtime);
	struct tm* timeinfo;
	
	timeinfo = localtime(&rawtime);
	sprintf(date , "%d/%d/%d %02d:%02d:%02d" , timeinfo->tm_mday , timeinfo->tm_mon , timeinfo->tm_year + 1900 , timeinfo->tm_hour , timeinfo->tm_min , timeinfo->tm_sec);
	return string(date);
}

void readConfig(string pFilePath) {
	ifstream fin(pFilePath);
	string logFileName;
	
	fin >> gMessageKey;
	fin >> gMessageType;
	fin >> gRemotePath;
	fin >> gLocalPath;
	fin >> logFileName;
	
	fin.close();
	
	gLogFile.open(logFileName.c_str());
	
	//cout << gMessageKey << " " << gMessageType << " " << gRemotePath << " " << gLocalPath << endl;
}

int main(int argc , char** argv) {
	assert(argc == 2);
	
	readConfig(argv[1]);
	
	MessageChannel channel(gMessageKey);
	SyncMessage *message = new SyncMessage(gMessageType);
	
	gLogFile << getCurrentDate() << " Starting synchronizer PID: " << getpid() << endl;
	cout << getCurrentDate() << " Starting synchronizer PID: " << getpid() << endl;
	
	while (1) {
		if (channel.receive(message , message->getLength()) >= 0) {
			gLogFile << getCurrentDate() << " Receiving sync request"<< endl;
			cout << getCurrentDate() << " Receiving sync request"<< endl;
			
			pid_t pid = fork();
			if (pid == 0) {
				execl("/usr/bin/rsync" , "rsync" , "-avz" , gRemotePath.c_str() , gLocalPath.c_str() , (char*)0);
				exit(0);
			}
			else {
				int status;
				waitpid(pid , &status , 0);
				
				gLogFile << getCurrentDate() << " Sync request done with status " << status << endl;
				cout << getCurrentDate() << " Sync request done with status " << status << endl;
			}			
		}
	}
	
	return 0;
}
